package com.qc.wintrax.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolylineOptions;
import com.qc.wintrax.BaseActivity;
import com.qc.wintrax.R;
import com.qc.wintrax.WTApplication;
import com.qc.wintrax.utils.LogUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;
import greendao.LineName;
import greendao.MapInfo;
import greendao.MarkerInfo;

import static android.R.attr.id;
import static com.loc.e.m;

public class EditMapInfoActivity extends BaseActivity implements LocationSource, AMapLocationListener {

    @Bind(R.id.map)
    MapView map;


    private AMap aMap;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private List<MapInfo> mapInfoList;
    private List<MarkerInfo> markerInfoList;
    private List<LatLng> points = new ArrayList<LatLng>();
    private Marker markers;
    private ArrayList<MarkerOptions> markerList = new ArrayList<MarkerOptions>();
    private ArrayList<Marker> mList = new ArrayList<Marker>();
    private List<LineName> lineNameList ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_map_info);
        ButterKnife.bind(this);
        initView();
        map.onCreate(savedInstanceState);// 此方法必须重写

    }

    private void initView() {
        if (aMap == null) {
            aMap = map.getMap();
//            aMap.moveCamera(CameraUpdateFactory.zoomTo(30));
            getValues();
//            setUpMap();
//            geocoderSearch = new GeocodeSearch(this);
//            geocoderSearch.setOnGeocodeSearchListener(this);
        }
    }

    public void getValues() {
        long id = getIntent().getLongExtra("id", 0);
        LineName lineNames = (LineName) getIntent().getSerializableExtra("lineName");
        String diss = lineNames.getMap_distance();
        String ttimes = lineNames.getMap_totalTime();
        LogUtil.e("获取的数据---aaaa---" + diss);
        LogUtil.e("获取的数据---bbbb---" + ttimes);

        LogUtil.e("获取的主键是---" + id);
//        mapInfoList = WTApplication.getGSDaoSession().getMapInfoDao().loadAll();
//        for (int i = 0; i < mapInfoList.size(); i++) {
//                MapInfo mapInfo = mapInfoList.get(i);
//                long a = mapInfo.getLine_id();
//                LogUtil.e("获取的线路主键是---"+a);
//            }
        mapInfoList = WTApplication.getGSDaoSession().getMapInfoDao().
                queryRaw("where line_id = ?", new String[]{id + ""});

        lineNameList = WTApplication.getGSDaoSession().getLineNameDao().
                queryRaw("where _id = ?", new String[]{id + ""});

        if (lineNameList!= null && lineNameList.size() >0){
            LineName lineName = lineNameList.get(0);
            String dis = lineName.getMap_distance();
            String ttime = lineName.getMap_totalTime();
            LogUtil.e("获取的数据---aaaa---" + dis);
            LogUtil.e("获取的数据---bbbb---" + ttime);
        }

        LogUtil.e("获取的数据--" + mapInfoList);
        if (mapInfoList != null && mapInfoList.size() > 0) {
//            historyTxt.setText(mapInfoList.toString());
            for (int i = 0; i < mapInfoList.size(); i++) {
                MapInfo mapInfo = mapInfoList.get(i);
//                int a = mapInfo.getMap_id();
                double lat = mapInfo.getMap_latitude();
                double lon = mapInfo.getMap_longitude();
                LatLng latLng = new LatLng(lat, lon);
                points.add(latLng);
                LogUtil.e("获取的经纬度---" + "---" + lat + "--------" + lon);
            }
            aMap.addPolyline(new PolylineOptions().color(Color.rgb(18, 184, 246)).
                    addAll(points).useGradient(true).width(15));
            Random random = new Random();
            int Info1 = random.nextInt(mapInfoList.size());
            MapInfo mapInfo1 = mapInfoList.get(Info1);
            double a = mapInfo1.getMap_latitude();
            double b = mapInfo1.getMap_longitude();
            //修改地图的中心点位置
            LatLng latLng = new LatLng(a,b);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
            aMap.moveCamera(CameraUpdateFactory.zoomTo(30));
        }

        markerInfoList = WTApplication.getGSDaoSession().getMarkerInfoDao().
                queryRaw("where line_id = ?", new String[]{id + ""});
        if (markerInfoList != null && markerInfoList.size() > 0) {
//            historyTxt.setText(mapInfoList.toString());
            for (int i = 0; i < markerInfoList.size(); i++) {
                MarkerInfo markerInfo = markerInfoList.get(i);
//                int a = mapInfo.getMap_id();
                double lat = markerInfo.getMarker_latitude();
                double lon = markerInfo.getMarker_longitude();
                String title = markerInfo.getMarker_titleName();
                LatLng latLng = new LatLng(lat, lon);
                BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.mipmap.map_zuobiao);
                MarkerOptions options = new MarkerOptions().position(latLng).title(title).icon(bitmap);
                // 在地图上添加Marker，并显示
                options.snippet(latLng.toString());
                options.draggable(true);
                options.perspective(true);
                options.draggable(true);
                markerList.add(options);
                markers = aMap.addMarker(options);
                mList.add(markers);
                aMap.addMarkers(markerList, true);
                LogUtil.e("获取的经纬度---" + "---" + lat + "--------" + lon);
            }
        }
    }

    private void setUpMap() {
        ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
//        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point1));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point2));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point3));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point4));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point5));
//        giflist.add(BitmapDescriptorFactory.fromResource(R.drawable.point6));
//        marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f).icons(giflist).period(50));
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
//        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_zuobiao));// 设置小蓝点的图标
//        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));// 设置圆形的填充颜色
//         myLocationStyle.anchor(int,int)//设置小蓝点的锚点
        myLocationStyle.strokeWidth(0);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationEnabled(true);
        // 设置定位的类型为定位模式 ，可以由定位 LOCATION_TYPE_LOCATE、
        // 跟随 LOCATION_TYPE_MAP_FOLLOW 或地图根据面向方向旋转 LOCATION_TYPE_MAP_ROTATE
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.getUiSettings().isCompassEnabled();
        aMap.getUiSettings().setCompassEnabled(true);
        aMap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                //定位成功回调信息，设置相关消息
//                LogUtil.e("开始获取的经纬度--a--" + a);
//                LogUtil.e("开始获取的经纬度--b--" + b);
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                aMapLocation.getLatitude();//获取纬度
                aMapLocation.getLongitude();//获取经度
//                LogUtil.e("结束获取的经纬度--a--" + a);
//                LogUtil.e("结束获取的经纬度--b--" + b);
                aMapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(aMapLocation.getTime());
                df.format(date);//定位时间
                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                aMapLocation.getCountry();//国家信息
                aMapLocation.getProvince();//省信息
                aMapLocation.getCity();//城市信息
                aMapLocation.getDistrict();//城区信息
                aMapLocation.getStreet();//街道信息
                aMapLocation.getStreetNum();//街道门牌号信息
                aMapLocation.getCityCode();//城市编码
                aMapLocation.getAdCode();//地区编码
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }

    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(this);
            mLocationOption = new AMapLocationClientOption();
            // 设置定位监听
            mlocationClient.setLocationListener(this);
            // 设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            // 设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        map.onPause();
        deactivate();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        map.onDestroy();
    }

}
